package message

import (
	"context"
	"math"

	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/code"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/setting/client/message"
	"github.com/zeromicro/go-zero/core/logc"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type NoticeMessageListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 公告消息列表
func NewNoticeMessageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NoticeMessageListLogic {
	return &NoticeMessageListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *NoticeMessageListLogic) NoticeMessageList(req *types.NoticeMessageListReq) (resp *types.NoticeMessageListDataRes, err error) {
	u, err := l.svcCtx.SettingService.Message.NoticeMessageList(l.ctx, &message.NoticeMessageListReq{
		Page:       req.Page,
		Size:       req.Size,
		Title:      req.Title,
		MerchantId: 1, // 商户ID
		Status:     -1,
		Type:       req.Type,
	})

	if err != nil {
		logc.Error(l.ctx, "NoticeMessageList err:", err)
		return nil, err
	}

	if u.Code != int64(code.SettingRpcSuccessful.Code()) {
		return nil, code.BusinessFailure
	}

	list := make([]types.NoticeMessageDataItemRes, 0)

	for _, v := range u.Data.List {
		list = append(list, types.NoticeMessageDataItemRes{
			Id:         v.Id,         // 主键ID
			MerchantId: v.MerchantId, // 商户ID
			Type:       v.Type,       // 消息类型,0:弹窗消息,1:滚动消息
			Title:      v.Title,      // 标题
			Content:    v.Content,    // 内容
			Status:     v.Status,     // 状态,0:禁用,1:启用
			UpdatedAt:  v.UpdatedAt,  // 修改时间
		})
	}

	return &types.NoticeMessageListDataRes{
		List: list,
		Pagination: types.Pagination{
			PageSize:  int32(req.Size),
			Page:      int32(req.Page),
			Total:     u.Data.Count,
			TotalPage: int64(math.Ceil(float64(u.Data.Count) / float64(u.Data.Size))),
		},
	}, nil
}
